package cn.springcloud.fix.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BeanWrapperUtil {

    public static <T> T copyProperties(Class<T> clazz, Object source, String... ignorePropertis) {
        if (source == null) {
            log.info("Source is null,Don't copy!");
            return null;
        }
        T dest = getInstance(clazz);
        copyProperties(source, dest, ignorePropertis);
        return dest;
    }

    public static <T> T getInstance(Class<T> destClass) {
        T dest = null;
        try {
            dest = destClass.newInstance();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return dest;
    }

    public static void copyProperties(Object source, Object dest, String... ignorePropertis) {
        if (source != null && dest != null) {
            BeanUtils.copyProperties(source, dest, ignorePropertis);
        } else {
            log.info("Source or Dest is null,Ignore it!");
        }
    }

    public static <T, E> List<E> convertList(List<T> list, Class<E> destClass) {
        List<E> destList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(list)) {
            for (T source : list) {
                E e = copyProperties(destClass, source);
                if (e != null) {
                    destList.add(e);
                }
            }
        }

        return destList;
    }
}
